package com.apestech.framework.json;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.RandomAccess;

import com.apestech.framework.file.BufferFile;
import com.apestech.framework.file.callback.ReadBufferFileCallBackHandler;
import com.apestech.framework.file.callback.WriteBufferFileCallBackHandler;

public class JSONArray extends JSON implements List<Object>, Cloneable, RandomAccess, Serializable {

	protected static final long  serialVersionUID = 1L;
    protected final List<Object> list;
    protected transient Object relatedArray;
    protected transient Type   componentType;
    private boolean bText=true; 
	private int count;
	private String fileName;
	private int lastSize=0;

	public JSONArray(){
        this.list = new ArrayList<Object>();
        this.count=0;
        this.fileName=getUUID();
    }

    public JSONArray(List<Object> list){
        this.list = list;
        this.count=list.size();
        this.fileName=getUUID();
    }
    
    public JSONArray(String jsonStr) throws Exception{
    	this.list=(List<Object>) parse(jsonStr, JSONArray.class);
    	this.count=this.list.size();
    	this.fileName=getUUID();
    }

    public JSONArray(JSONObject json) throws Exception{
        this.list = new ArrayList<Object>();
        this.list.add(json);
        this.count=this.list.size();
        this.fileName=getUUID();
    }

    public JSONArray(int initialCapacity){
        this.list = new ArrayList<Object>(initialCapacity);
        this.count=this.list.size();
        this.fileName=getUUID();
    }
    
    private void writeTextData() throws Exception{
    	this.lastSize=this.list.size();
    	BufferFile file=new BufferFile(this.fileName+this.count);
		file.write(new WriteBufferFileCallBackHandler(){
			int i=0;
			int len=list.size();
			@Override
			public boolean canWrite() throws Exception {
				return i<len;
			}

			@Override
			public String write(int index) throws Exception {
				i=index;
				return JSON.toJSONString(list.get(i));
			}
		});
		this.list.clear();
		this.count++;
		file=null;
    }

    /**
     * @since 1.1.16
     * @return
     */
    public Object getRelatedArray() {
        return relatedArray;
    }

    public void setRelatedArray(Object relatedArray) {
        this.relatedArray = relatedArray;
    }

    public Type getComponentType() {
        return componentType;
    }

    public void setComponentType(Type componentType) {
        this.componentType = componentType;
    }

    public int size() {
        return list.size();
    }

    public boolean isEmpty() {
        return list.isEmpty();
    }

    public boolean contains(Object o) {
        return list.contains(o);
    }

    public Iterator<Object> iterator() {
        return list.iterator();
    }

    public Object[] toArray() {
        return list.toArray();
    }

    public <T> T[] toArray(T[] a) {
        return list.toArray(a);
    }

    public boolean add(Object e) {
    	return list.add(e);
    }
    
    public boolean add(String json) throws Exception{
    	return list.add(JSON.toJSON(json));
    }

    public JSONArray fluentAdd(Object e) {
    	list.add(e);
        return this;
    }

    public boolean remove(Object o) {
        return list.remove(o);
    }

    public JSONArray fluentRemove(Object o) {
        list.remove(o);
        return this;
    }

    public boolean containsAll(Collection<?> c) {
        return list.containsAll(c);
    }

    public boolean addAll(Collection<? extends Object> c) {
    	return list.addAll(c);
    }

    public JSONArray fluentAddAll(Collection<? extends Object> c) {
    	list.addAll(c);
        return this;
    }

    public boolean addAll(int index, Collection<? extends Object> c) {
    	return list.addAll(index, c);
    }

    public JSONArray fluentAddAll(int index, Collection<? extends Object> c) {
    	list.addAll(index, c);
        return this;
    }

    public boolean removeAll(Collection<?> c) {
    	return list.removeAll(c);
    }

    public JSONArray fluentRemoveAll(Collection<?> c) {
    	list.removeAll(c);
        return this;
    }

    public boolean retainAll(Collection<?> c) {
        return list.retainAll(c);
    }

    public JSONArray fluentRetainAll(Collection<?> c) {
        list.retainAll(c);
        return this;
    }

    public void clear() {
    	this.count=0;
        list.clear();
    }

    public JSONArray fluentClear() {
    	this.count=0;
        list.clear();
        return this;
    }

    public Object set(int index, Object element) {
        if (index == -1) {
            list.add(element);
            return null;
        }
        if (list.size() <= index) {
            for (int i = list.size(); i < index; ++i) {
                list.add(null);
            }
            list.add(element);
            return null;
        }
        return list.set(index, element);
    }

    public JSONArray fluentSet(int index, Object element) {
        set(index, element);
        return this;
    }

    public void add(int index, Object element) {
    	list.add(index, element);
    }

    public JSONArray fluentAdd(int index, Object element) {
    	list.add(index, element);
        return this;
    }

    public Object remove(int index) {
        return list.remove(index);
    }

    public JSONArray fluentRemove(int index) {
        list.remove(index);
        return this;
    }

    public int indexOf(Object o) {
        return list.indexOf(o);
    }

    public int lastIndexOf(Object o) {
        return list.lastIndexOf(o);
    }

    public ListIterator<Object> listIterator() {
        return list.listIterator();
    }

    public ListIterator<Object> listIterator(int index) {
        return list.listIterator(index);
    }

    public List<Object> subList(int fromIndex, int toIndex) {
        return list.subList(fromIndex, toIndex);
    }

    public JSONObject get(int index) {
        try {
            if(list.get(index)==null) return null;
            if(list.get(index) instanceof JSONObject) return (JSONObject) list.get(index);
            return JSON.toJSON(list.get(index));
        } catch (Exception e) {
        }
        return null;
    }

    public JSONObject getJSONObject(int index) throws Exception {
        Object value = list.get(index);
        if (value instanceof JSONObject) {
            return (JSONObject) value;
        }
        return (JSONObject) toJSON(value);
    }

    public JSONArray getJSONArray(int index) throws Exception {
        Object value = list.get(index);
        if (value instanceof JSONArray) {
            return (JSONArray) value;
        }
        return (JSONArray) toJSONArray(value);
    }

    public <T> T getObject(int index, Class<T> clazz) throws Exception {
        Object obj = list.get(index);
        return parse(obj, clazz);
    }

    public <T> T getObject(int index, Type type) throws Exception {
        Object obj = list.get(index);
        if (type instanceof Class) {
            return (T) parse(obj, (Class) type);
        } else {
            String json = JSON.toJSONString(obj);
            return (T) parse(json, (Class) type);
        }
    }

    public Boolean getBoolean(int index) throws Exception {
        Object value = get(index);
        if (value == null) {
            return null;
        }
        return castToBoolean(value);
    }

    public boolean getBooleanValue(int index) throws Exception {
        Object value = get(index);
        if (value == null) {
            return false;
        }
        return castToBoolean(value).booleanValue();
    }

    public Byte getByte(int index) throws Exception {
        Object value = get(index);
        return castToByte(value);
    }

    public byte getByteValue(int index) throws Exception {
        Object value = get(index);
        if (value == null) {
            return 0;
        }
        return castToByte(value).byteValue();
    }

    public Short getShort(int index) throws Exception {
        Object value = get(index);
        return castToShort(value);
    }

    public short getShortValue(int index) throws Exception {
        Object value = get(index);
        if (value == null) {
            return 0;
        }
        return castToShort(value).shortValue();
    }

    public Integer getInteger(int index) throws Exception {
        Object value = get(index);
        return castToInt(value);
    }

    public int getIntValue(int index) throws Exception {
        Object value = get(index);
        if (value == null) {
            return 0;
        }
        return castToInt(value).intValue();
    }

    public Long getLong(int index) throws Exception {
        Object value = get(index);
        return castToLong(value);
    }

    public long getLongValue(int index) throws Exception {
        Object value = get(index);
        if (value == null) {
            return 0L;
        }
        return castToLong(value).longValue();
    }

    public Float getFloat(int index) throws Exception {
        Object value = get(index);
        return castToFloat(value);
    }

    public float getFloatValue(int index) throws Exception {
        Object value = get(index);
        if (value == null) {
            return 0F;
        }
        return castToFloat(value).floatValue();
    }

    public Double getDouble(int index) throws Exception {
        Object value = get(index);
        return castToDouble(value);
    }

    public double getDoubleValue(int index) throws Exception {
        Object value = get(index);
        if (value == null) {
            return 0D;
        }
        return castToDouble(value);
    }

    public BigDecimal getBigDecimal(int index) {
        Object value = get(index);
        return castToBigDecimal(value);
    }

    public BigInteger getBigInteger(int index) {
        Object value = get(index);
        return castToBigInteger(value);
    }

    public String getString(int index) {
        Object value = get(index);
        return castToString(value);
    }

    public java.util.Date getDate(int index) throws Exception {
        Object value = get(index);
        return castToDate(value);
    }

    public java.sql.Date getSqlDate(int index) throws Exception {
        Object value = get(index);
        return castToSqlDate(value);
    }

    public java.sql.Timestamp getTimestamp(int index) throws Exception {
        Object value = get(index);
        return castToTimestamp(value);
    }

    @Override
    public Object clone() {
        return new JSONArray(new ArrayList<Object>(list));
    }

    public boolean equals(Object obj) {
        return this.list.equals(obj);
    }

    public int hashCode() {
        return this.list.hashCode();
    }
    
    public String toString(){
    	try {
			return toJSONString(this.list);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return "";
    }
    
    public void setKeyFieldValue(String keyField, String key, String field, Object value){
    	int len=this.list.size();
    	for(int i=0; i<len; i++){
    		JSONObject map=(JSONObject) this.list.get(i);
    		if(map.getString(keyField).equals(key)){
    			map.put(field, value);
    			break;
    		}
    	}
    }
}

